package com.xj.openapi4j.service.token;

import com.fasterxml.jackson.core.type.TypeReference;
import com.xj.isv.crypto.SignHelper;
import com.xj.isv.model.AccessTokenResponse;
import com.xj.isv.model.GenericResponse;
import com.xj.isv.service.OpenApiRequestService;
import com.xj.isv.utils.RequestTool;
import com.xj.util.Constance;
import com.xj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Service
@Slf4j
public class YsToken {

    @Value("${AppKey}")
    String  AppKey;

    @Value("${AppSecret}")
    String  suiteSecret;

    @Value("${tenantId}")
    String  tenantId;
    @Autowired
    RedisTemplate redisTemplate;

    public  void    regetToken() throws Exception{
        String suiteTicket="";
        Map<String, String> params = new HashMap<>();
        params.put("appKey", AppKey);
        //   params.put("tenantId", tenantId);
        //   params.put("suiteTicket", suiteTicket);
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        // 计算签名
        String signature = SignHelper.sign(params, suiteSecret);
        //  String signature =java.net.URLEncode(Base64(HmacSHA256(params)));
        params.put("signature", signature);
        // 请求
        String requestUrl =  "https://c3.yonyoucloud.com/iuap-api-auth/open-auth/selfAppAuth/getAccessToken";
        //  String requestUrl = openApiUrl + "iuap-api-auth/open-auth/selfAppAuth/getAccessToken";
        GenericResponse<AccessTokenResponse> response = RequestTool.doGet(requestUrl, params, new TypeReference<GenericResponse<AccessTokenResponse>>() {});
        log.info(String.valueOf(response));
         if("00000".equals(response.getCode())){
             AccessTokenResponse accessTokenResponse=     response.getData();
             long  expire=  accessTokenResponse.getExpire();
             String token=   accessTokenResponse.getAccessToken();
             redisTemplate.opsForValue().set(Constance.ystoken,token, Duration.ofSeconds(expire));
         }else {
             throw  new Exception(response.getMessage());
         }
    }


   public String  getToken() throws Exception{
        boolean  isexist=redisTemplate.hasKey(Constance.ystoken);
        if(!isexist){
            regetToken();
        }
        String  token=(String)redisTemplate.opsForValue().get(Constance.ystoken);
        if(StringUtils.isNotEmpty(token)){
            return  token;
        }else {
            throw  new Exception("获取U8token 失败!");
        }


   }


}
